<template>
    <template v-if="formatType=='button'" >
     <Upload  
        :default-file-list="defaultList"
        :on-success="handleSuccess"
        :format="fileFormat"
        :max-size="maxSize"
        :on-format-error="handleFormatError"
        :on-exceeded-size="handleMaxSize"
        :before-upload="handleBeforeUpload"
        :data="token"
        action="//up-z0.qiniup.com/"
        multiple>
      <sort name="Button"><Button icon="ios-cloud-upload-outline">上传文件</Button></sort>
     </Upload>
    </template>

   <template v-else>
    <div class="upload-list" v-for="(item,index) in uploadList" :key="index">
        <template v-if="item.status === 'finished'">
            <Image :src="item.url" fit="cover" width="100%" height="100%" />
            <div class="upload-list-cover">
                <Icon type="ios-eye-outline" @click="handleView(item.url)"></Icon>
                <Icon type="ios-trash-outline" @click="handleRemove(item)"></Icon>
            </div>
        </template>
        <template v-else>
            <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
        </template>
    </div>
    <Upload
        :ref="columnKey"
        v-if="uploadList.length < maxNum"
        :show-upload-list="false"
        :default-file-list="defaultList"
        :on-success="handleSuccess"
        :format="fileFormat"
        :max-size="maxSize"
        :on-format-error="handleFormatError"
        :on-exceeded-size="handleMaxSize"
        :before-upload="handleBeforeUpload"
        :data="token"
        multiple
        type="drag"
        action="//up-z0.qiniup.com/"
        style="display:inline-block;width:98px;">
        <div class="uploadBtn">
            <Icon type="ios-camera" color="#ccc" size="30"></Icon>
        </div>
    </Upload>
      <Modal v-model="visible" footer-hide width="50">
        <img :src="previewUrl" class="previewImgSty" /> 
      </Modal>
  </template>
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  import { getUploadToken} from '@api/netTool';

  export default defineComponent({
    name:'photo-upload',
        props:{
          modelVal:{
            type:String,
            default:''
          },
          maxNum:{
            type:[Number,String],
            default:1
          },
          maxSize:{
            type:[Number,String],
            default:2048
          },
          fileFormat:{
            type:Array,
            default:() => {['jpg','jpeg','png']}
          },
          columnKey:{
            type:String,
            default:''
          },
          formatType:{
            type:String,
            default:''
          }
        },
        data () {
            return {
                previewUrl: '',
                token:{},
                prefix:'',
                visible: false,
                defaultList:[],
                uploadList:[],
                refsUp:null
            }
        },
        emits: ['setColumnKeyVal'],
        mounted () {
          const { token } = JSON.parse(localStorage.getItem('qiniu')) || {}
          this.token = {token:token};
          const randStr= Math.floor(Math.random()*5000)
          setTimeout(() => { this.getUploadTokenApi(); },randStr)
        },
        watch:{
          uploadList:{
            immediate:true,
            deep:true,
            handler(nVal){
              let value:any=[];
              nVal.map((item)=>{
                value.push(item.url);
              })
              this.$emit('setColumnKeyVal',{key:this.columnKey,value:value});
            }
          },
          modelVal:{
            immediate:true,
            deep:true,
            handler(nVal){
             this.defaultList = [];
             if(!Array.isArray(nVal) && nVal){
                this.uploadList=[];
                let imgList = nVal.split(',');
                let imgAry = [];
                imgList.map((item,index) => {
                  imgAry.push({url:item, name:index,percentage:100,status:"finished",uid:Date.now()})
                })
                this.uploadList = imgAry;
              }else{
                this.uploadList= []
              }
            }
           }  
        },
        methods: {
            handleView (url) {
                this.previewUrl=url;
                this.visible = true;
            },
            handleRemove (file) {
                let index  = this.uploadList.indexOf(file);
                this.uploadList.splice(index, 1);
            },
            handleSuccess (res, file) {
                const { prefix } = JSON.parse(localStorage.getItem('qiniu')) || {}
                let imgAry = this.uploadList;
                imgAry.push({url:prefix+'/'+res.key, name:res.key,percentage:100,status:"finished",uid:Date.now()})
                this.uploadList = imgAry
            },
            handleFormatError () {
                this.$Notice.warning({
                    title: '提示',
                    desc: '你上传的文件格式不正确'
                });
            },
            handleMaxSize () {
                this.$Notice.warning({
                    title: '提示',
                    desc: '你上传的文件大小超过限制'
                });
            },
            handleBeforeUpload (file) {
                console.log(file)
                let fileNameFormat =  file['name'].split(',');
                if(fileNameFormat.length > 1){
                  this.$Notice.warning({
                       title: '文件名格式异常，请修改后上传！'
                  });
                  return false;
                }
                
                const check = this.uploadList.length < this.maxNum;
                if (!check) {
                    this.$Notice.warning({
                       title: '你上传的文件个数超过限制'
                    });
                }
                return check;
            },
            getUploadTokenApi(){
            const { timestamp } = JSON.parse(localStorage.getItem('qiniu')) || {}
            if(timestamp && ((Date.now()-timestamp)/1000) < 7000){ return false; } 

            return new Promise((resolve, reject) => {
              getUploadToken({}).then(res => { 
                localStorage.setItem('qiniu', JSON.stringify({
                  token: res['token'],
                  prefix: res['url'],
                  timestamp:Date.now()
                }))
                const { token } = JSON.parse(localStorage.getItem('qiniu')) || {}
                this.token = {token:token};
              }).catch(err => {
                  reject(err);
              });
            });
          },
        }
    })
</script>
<style>
.previewImgSty{ width:100%; height: auto; max-height: 600px; padding-top:30px;}
    .uploadBtn{width:98px;height:98px;line-height: 98px;}
    .upload-list{
        display:block;
        float:left;
        width: 100px;
        height: 100px;
        text-align: center;
        line-height: 100px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 10px;
        margin-bottom: 10px;
    }
    .fupload-list img{
        width: 100%;
        height: 100%;
    }
    .upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .upload-list:hover .upload-list-cover{
        display: block;
    }
    .upload-list-cover i{
        color: #fff;
        font-size: 30px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>